<template>
  <div class="rent-index">
    <!-- 头部导航栏 -->
    <navbar-comm title="发布房源"></navbar-comm>
    <!-- /头部导航栏 -->
    <!-- 主体内容 -->
    <!-- 标题 -->
    <van-cell value="房源信息" class="title" />
    <!-- 小区名称 -->
    <van-field
      label="小区名称"
      readonly
      clickable
      @click="$router.push('/rent/search')"
    >
      <template #extra>
        <i v-if="$route.query?.community">{{
          $route.query?.community.communityName
        }}</i>
        <i v-else>请输入小区名称&nbsp;</i>
        <van-icon name="arrow"></van-icon>
      </template>
    </van-field>
    <!-- 租金~朝向 -->
    <Detailss
      @show-house-type="isShowHouseType = true"
      @show-floor="isShowFloor = true"
      @show-rientation="isShowoRientation = true"
      :isFloor="isFloor"
      :isHouseType="isHouseType"
      :isOrientation="isOrientation"
    />
    <!-- /租金~朝向 -->
    <!-- 房屋图像&房屋配置 -->
    <Img />
    <Icon />
    <!-- 房屋描述 -->
    <div>
      <van-cell title="房屋描述" class="describe" />
      <van-field
        v-model="describe"
        rows="5"
        autosize
        type="textarea"
        placeholder="请输入房屋描述信息"
        show-word-limit
        @blur="onBlurDescribe"
      />
    </div>
    <!-- 底部栏 -->
    <div class="footer-bar">
      <div class="cancel" @click="$router.push('/ ')">取消</div>
      <div class="confirm" @click="onSubmit">确定</div>
    </div>
    <!-- /主体内容 -->
    <!-- 弹出层 -->
    <!-- 户型 -->
    <van-popup
      v-model="isShowHouseType"
      position="bottom"
      :style="{ height: '45%' }"
    >
      <van-picker
        show-toolbar
        :columns="columns1"
        @confirm="onConfirmHouseType"
        @cancel="isShowHouseType = false"
      />
    </van-popup>
    <!-- 建筑面积 -->
    <van-popup
      v-model="isShowFloor"
      position="bottom"
      :style="{ height: '45%' }"
    >
      <van-picker
        show-toolbar
        :columns="columns2"
        @confirm="onConfirmFloor"
        @cancel="isShowFloor = false"
      />
    </van-popup>
    <!-- 朝向 -->
    <van-popup
      v-model="isShowoRientation"
      position="bottom"
      :style="{ height: '45%' }"
    >
      <van-picker
        show-toolbar
        :columns="columns3"
        @confirm="onConfirmRientation"
        @cancel="isShowoRientation = false"
      />
    </van-popup>
    <!-- /弹出层 -->
  </div>
</template>

<script>
// 引入组件
import NavbarComm from '@/components/NavbarComm.vue'
import Detailss from '@/views/rent/components/Detailss.vue'
import Img from '@/views/rent/components/Img.vue'
import Icon from '@/views/rent/components/Icon.vue'
// 引入vuex
import { mapState, mapMutations, mapGetters } from 'vuex'
// 引入请求方法
import { getHouseConditionApi, PublishListingsApi } from '@/api'
export default {
  name: 'rentIndex',
  components: { NavbarComm, Detailss, Img, Icon },
  props: {},
  data() {
    return {
      describe: '',
      isShowHouseType: false,
      isShowFloor: false,
      isShowoRientation: false,
      columns1: [],
      columns2: [],
      columns3: [],
      data: [],
      isFloor: '',
      isHouseType: '',
      isOrientation: '',
      updateRentHouseConditions: {
        title: null,
        description: null,
        houseImg: null,
        oriented: null,
        supporting: null,
        price: null,
        roomType: null,
        size: null,
        floor: null,
        community: null
      },
      community: this.$route.query.community?.community
    }
  },
  computed: {
    ...mapState(['curentCityObj']),
    ...mapState(['rentHouse']),
    ...mapState(['token']),
    ...mapGetters(['isLogin'])
  },
  watch: {},
  created() {
    // // 第一次进页面和刷新时获取房屋查询/上传条件渲染页面
    this.getHouseConditionFn()
    // 刷新和第一次进入页面清空初始化本地和vuex发布房屋所需条件
    this.updateRentHouse(this.updateRentHouseConditions)
  },
  methods: {
    ...mapMutations(['updateRentHouse']),
    // 确认发布
    async onSubmit() {
      if (this.isLogin) {
        try {
          const obj = this.rentHouse
          if (!obj.houseImg) return this.$toast.fail('请添加房屋图片')
          obj.community = this.community
          console.log(obj)
          this.updateRentHouse(obj)
          const { data } = await PublishListingsApi(obj)
          console.log(data)
          // 更新清空本地和vuex的请求参数，以便下一次可以正常发请求
          this.updateRentHouse(this.updateRentHouseConditions)
          this.$dialog
            .confirm({
              title: '提示',
              message: '房源发布成功',
              confirmButtonText: '继续发布',
              cancelButtonText: '去查看'
            })
            .then(() => {
              // on confirm  确认键
              // this.$router.push('/rent')
              // 因为跳转回原页面数据视图数据不会改变，借助该方法自己创建一个文件过度，强制刷新页面，需要配置路由
              this.$router.replace('/refresh')
            })
            .catch(() => {
              // on cancel 取消键
              this.$router.push('/home/wholerent')
            })
          this.$toast.success('发布成功')
        } catch (err) {
          if (err?.response?.statuse === 400) {
            this.$toast.fail('请先登录!')
          } else {
            this.$toast.fail('发布失败, 请重试!')
          }
        }
      }
    },
    //户型确认
    onConfirmHouseType(val) {
      // console.log('户型', val)
      // console.log(this.data.roomType)
      // 用obj过度，最好不要直接改vuex里面state值
      const obj = this.rentHouse
      this.data.roomType.forEach((item) => {
        if (item.label === val) {
          obj.roomType = item.value
        }
      })
      // 更新本地数据
      this.updateRentHouse(obj)
      // 关闭弹层
      this.isShowHouseType = false
      // 更新视图
      this.isHouseType = val
    },
    // 楼层确认
    onConfirmFloor(val) {
      // console.log(val)
      const obj = this.rentHouse
      this.data.floor.forEach((item) => {
        if (item.label === val) {
          obj.floor = item.value
        }
      })
      this.updateRentHouse(obj)
      this.isShowFloor = false
      // console.log('楼层', val)
      this.isFloor = val
    },
    // 朝向确认
    onConfirmRientation(val) {
      // console.log(val)
      const obj = this.rentHouse
      this.data.oriented.forEach((item) => {
        if (item.label === val) {
          obj.oriented = item.value
        }
      })
      this.updateRentHouse(obj)
      this.isShowoRientation = false
      this.isOrientation = val
    },

    // 获取房屋查询/上传条件渲染页面
    async getHouseConditionFn() {
      this.$toast.loading({
        message: '数据加载中...',
        forbidClick: true
      })
      const { data } = await getHouseConditionApi({
        id: this.curentCityObj.value
      })
      //   console.log(data)
      this.dealColumns(this.columns1, data.body.roomType)
      this.dealColumns(this.columns2, data.body.floor)
      this.dealColumns(this.columns3, data.body.oriented)
      // 保存数据
      this.data = data.body
    },
    //预处理3个columns中的数据
    dealColumns(columns, arr) {
      arr.forEach((item) => {
        columns.push(item.label)
      })
    },
    onBlurDescribe() {
      if (this.describe) {
        const obj = this.rentHouse
        obj.description = this.describe
        this.updateRentHouse(obj)
      }
    },
    mounted() {}
  }
}
</script>

<style scoped lang="less">
.rent-index {
  background-color: #f6f5f6;
  padding-bottom: 1.7rem;
  :deep(.van-cell) {
    border-bottom: 1px solid #ddd;
  }
  :deep(.van-cell__value--alone) {
    color: #21b97a;
    font-size: 30px;
  }
  .describe {
    margin-top: 4.3rem;
  }
  .footer-bar {
    position: fixed;
    left: 0;
    bottom: 0;
    display: flex;
    width: 100%;
    height: 85px;
    border-top: 1px solid #eee;
    text-align: center;
    line-height: 85px;
    .cancel {
      flex: 1;
      background-color: #fff;
      color: #21b97a;
      font-size: 30px;
    }
    .confirm {
      flex: 1;
      background-color: #21b97a;
      color: #fff;
      font-size: 30px;
    }
  }
}
</style>
